﻿using GameProtocol.Protocol;
using Google.Protobuf;
using System;
using System.Collections.Generic;
using System.Net;
using UnityEngine;
using UnityEngine.Events;

namespace GameLogic
{
    public class NetClient
    {
        protected bool m_HasHandshake = false;
        protected Dictionary<GameProtocol.Protocol.CSMsgId, UnityEvent<IPEndPoint, byte[]>> m_ReceiveEvents = new Dictionary<GameProtocol.Protocol.CSMsgId, UnityEvent<IPEndPoint, byte[]>>();
        protected uint m_ConversationID = 0;

        public virtual void Init(int receivePort, IPEndPoint sendEndPoint)
        {
            m_ConversationID = GlobalFunction.GetRandomID();
            m_HeartTimeoutCount = 0;
            AddListener(CSMsgId.HeartJumpRsp, OnHeartJumpRsp);
        }
        public UnityAction<IPEndPoint, byte[]> AddListener(GameProtocol.Protocol.CSMsgId type, UnityAction<IPEndPoint, byte[]> action)
        {
            if (!m_ReceiveEvents.ContainsKey(type))
                m_ReceiveEvents.Add(type, new UnityEvent<IPEndPoint, byte[]>());
            m_ReceiveEvents[type].AddListener(action);
            return action;
        }
        public virtual void Disconnect()
        {
        }
        public virtual void Clear()
        {

        }
        public void RemoveListener(GameProtocol.Protocol.CSMsgId type, UnityAction<IPEndPoint, byte[]> action)
        {
            if (!m_ReceiveEvents.ContainsKey(type))
                return;
            m_ReceiveEvents[type].RemoveListener(action);
        }
        protected virtual void Send(byte[] data, int length)
        {
        }
        public virtual void Send(GameProtocol.Protocol.CSMsgId id, byte[] data)
        {
        }
        protected virtual void OnReceived(IPEndPoint ep, byte[] data, int offset, int length)
        {
        }

        float m_HeartTimeoutCount = 0;
        float m_HeartJumpTimeCount = 0;
        public virtual void Update()
        {
            if(m_HasHandshake)
            {
                if (m_HeartTimeoutCount > 7)
                {
                    OnConnectTimeout();
                }
                m_HeartJumpTimeCount += Time.unscaledDeltaTime;
                m_HeartTimeoutCount += Time.unscaledDeltaTime;
                if (m_HeartJumpTimeCount > .7f)
                {
                    m_HeartJumpTimeCount = 0;
                    HeartJumpRqrData hearJumpData = new HeartJumpRqrData();
                    Send(CSMsgId.HeartJumpRqr, hearJumpData.ToByteArray());
                }
            }
        }

        public virtual string GetLocalIP()
        {
            return "";
        }
        public virtual void Handshake()
        {
        }

        public void OnHeartJumpRsp(IPEndPoint ep, byte[] data)
        {
            m_HeartTimeoutCount = 0;
        }

        public void OnConnectTimeout()
        {
            Debug.Log("连接超时~~~~！");
        }
    }
}
